package com.lerning.edu.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.lerning.edu.beans.SysUser;
import com.lerning.edu.beans.WorkOrder;
import com.lerning.edu.beans.WorkOrderAuditRecord;
import com.lerning.edu.commons.util.DateUtil;
import com.lerning.edu.commons.util.StringUtil;
import com.lerning.edu.manage.common.EmailSend;
import com.lerning.edu.manage.context.GlobalContext;
import com.lerning.edu.manage.util.UserUtils;
import com.lerning.edu.services.StudentService;
import com.lerning.edu.services.WorkOrderAuditRecordService;
import com.lerning.edu.services.WorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiangwei
 * @since 18/9/14
 */
@Controller
@RequestMapping("workOrderCost")
public class WorkOrderCostController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private WorkOrderAuditRecordService workOrderAuditRecordService;

    @RequestMapping("/apply")
    public String apply(HttpServletRequest request, String employeeId) {

        HttpSession session = request.getSession();

        if(session.getValue(employeeId) != null){
            String value = session.getValue(employeeId).toString();

            if(session.getValue(employeeId) != null && !("").equals(session.getValue(employeeId)) && (employeeId).equals(value)){
                request.setAttribute("isLogin", "N");
            }else{
                request.setAttribute("isLogin", "Y");
            }
        }else {
            request.setAttribute("isLogin", "Y");
        }

        List employees = new ArrayList();
        Map employee = new HashMap();

        if (StringUtil.isEmpty(employeeId)) {
            SysUser user = UserUtils.getUser();
            String account = user.getAccount();
            employees = workOrderService.queryEmployeeByCfield(account);
        } else {
            employees = workOrderService.queryEmployeeByUserID(employeeId);
        }

        if (employees.size() > 0) {
            employee = (HashMap) employees.get(0);
            if (!employee.get("cValue").equals("OA_OAS")) {
                return "/WorkOrderChangeSchool/view";
            }
        } else {
            return "/WorkOrderChangeSchool/view";
        }

        request.setAttribute("tEmployeeID", employeeId);
        return "WorkOrderCost/apply";
    }

    @RequestMapping("/findStudentAndReceipt")
    @ResponseBody
    public JSONObject findStudentAndReceipt(
            @RequestParam(value = "userId", required = false) String userId) {

        Map map = new HashMap();
        map.put("userId", userId);

        Map student = studentService.findStudentOne(map);
        List receipts = studentService.queryReceipt(map);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", receipts);
        jsonObject.put("student", student);

        return jsonObject;
    }

    @RequestMapping("/save")
    public String save(HttpServletRequest request,
                       @RequestParam(value = "tEmployeeID", required = false) String tEmployeeID,
                       @RequestParam(value = "userId", required = false) String userId,
                       @RequestParam(value = "classID", required = false) String classID,
                       @RequestParam(value = "userIdReceive", required = false) String userIdReceive,
                       @RequestParam(value = "crecoverydate", required = false) String cRecoveryDate,
                       @RequestParam(value = "courseTime", required = false) String courseTime,
                       @RequestParam(value = "courseMoney", required = false) String courseMoney,
                       @RequestParam(value = "cremarks", required = false) String cRemarks) throws Exception{

        WorkOrder workOrder = new WorkOrder();
        String employeeName = "陈尧尧";

        if (StringUtil.isEmpty(tEmployeeID)) {
            SysUser user = UserUtils.getUser();
            List employees = workOrderService.queryEmployeeByCfield(user.getAccount());

            if (employees.size() > 0) {
                Map employee = (HashMap) employees.get(0);
                tEmployeeID = employee.get("cUserID").toString();

                employeeName = employee.get("cName").toString();
            } else {
                tEmployeeID = "3378BBC1-8313-4023-9D15-5C8C58BD66A6";
            }
        }

        workOrder.setCcreateuser(tEmployeeID.trim());
        workOrder.setCuserid(userId.trim());
        workOrder.setCclassid(classID.trim());
        workOrder.setCstatus(1);
        workOrder.setCtype(6);//转费
        workOrder.setCrecoverydate(DateUtil.formateStringToDate(cRecoveryDate));
        workOrder.setCisoriginal(0);
        workOrder.setCremarks(cRemarks.trim());
        workOrder.setCisprint(2);
        workOrder.setCreason(userIdReceive.trim());//接收转费学员id

        workOrder.setResumeClassID(courseTime.trim());//转让课次
        workOrder.setChangeCampusID(courseMoney.trim());//课单价

        workOrder.setCcreatedate(new Date());

        Map map = new HashMap();
        map.put("userId", userId.trim());
        Map users = workOrderService.queryByUserId(map);
        workOrder.setCampus(users.get("cName").toString());

        map.put("campus", workOrder.getCampus());
        Map maxOrderNo = workOrderService.queryMaxOrderNo(map);

        String orderNo = DateUtil.getYear().substring(2, 4) + users.get("cAddress").toString();
        String oderNoNew = "";
        if (maxOrderNo == null) {
            oderNoNew = orderNo + "0001";
            workOrder.setCorderno(oderNoNew);
        } else {
            String oNo = maxOrderNo.get("cOrderNo").toString();
            oderNoNew = orderNo + StringUtil.autoGenericCode(oNo.substring(oNo.length() - 4, oNo.length()), 4);
            workOrder.setCorderno(orderNo + StringUtil.autoGenericCode(oNo.substring(oNo.length() - 4, oNo.length()), 4));
        }

        workOrderService.add(workOrder);

        List sendEmailUser = new ArrayList();

        sendEmailUser.add(GlobalContext.getProperties("EmailUserOfCost"));

        StringBuffer sendContent = new StringBuffer("您好! <br> ");

        sendContent.append("单据编号：" + oderNoNew + "，申请人：" + employeeName + "，请登录校管家及时处理。");

        String from = "特况单任务提醒";
        String title = "你有新特况单任务！";

        //发送邮件
        EmailSend.emailSend(sendEmailUser, from, title, sendContent.toString());


        return "redirect:/workOrderInterrupt/listPage?employeeId=" + tEmployeeID;
    }

    @RequestMapping("/detail")
    public String detail(HttpServletRequest request, String orderNo, String userID, String flag) {

        String returnValue = "WorkOrderCost/detail";

        Map map = new HashMap();
        map.put("orderNo", orderNo);
        Map workOrderDetail = workOrderService.queryDetail(map);

        if (workOrderDetail == null) {
            returnValue = "WorkOrderCost/auditPage";
            workOrderDetail = workOrderService.queryDetail1(map);
        } else if (workOrderDetail.get("cStatus").toString().equals("2")) {
            returnValue = "WorkOrderCost/operation";
        } else if (workOrderDetail.get("cStatus").toString().equals("4")) {
            returnValue = "WorkOrderCost/printPage";
        }

        map.put("userID", workOrderDetail.get("cUserID"));
        map.put("userId", workOrderDetail.get("cUserID"));

        Map student = studentService.findStudentOne(map);

        Map costMap = new HashMap();
        costMap.put("userId", workOrderDetail.get("cReason"));

        //转让学员信息

        BigDecimal balance = new BigDecimal("0.00");
        List receipts = studentService.queryReceipt(map);

        Map walletMoney = studentService.queryElectronicBalance(map);

        if (receipts.size() > 0) {
            for (Object obj : receipts) {
                Map receiptsMap = (HashMap) obj;
                balance = balance.add(new BigDecimal(receiptsMap.get("cRemainMoney").toString()));
            }
        }

        if (walletMoney != null) {
            student.put("walletMoney", walletMoney.get("cMoney"));
            balance = balance.add(new BigDecimal(walletMoney.get("cMoney").toString()));
        } else {
            student.put("walletMoney", 0);
        }

        student.put("totalMoney", balance);

        //接收学员信息
        Map mapReceive = new HashMap();
        mapReceive.put("userId", workOrderDetail.get("cReason"));
        mapReceive.put("classID", workOrderDetail.get("cClassID"));

        Map studentReceive = studentService.findStudentOne(map);

        Map classByCost = studentService.queryClassByCost(mapReceive);

        WorkOrderAuditRecord woar = new WorkOrderAuditRecord();
        woar.setCworkorderid(workOrderDetail.get("cID").toString());
        List record = workOrderAuditRecordService.queryList(woar);

        request.setAttribute("workOrderDetail", workOrderDetail);

        request.setAttribute("student", student);
        request.setAttribute("studentReceive", studentReceive);

        request.setAttribute("receipts", receipts);
        request.setAttribute("classByCost", classByCost);

        BigDecimal wMoney = new BigDecimal(workOrderDetail.get("changeCampusID").toString());
        BigDecimal tMoney = new BigDecimal(workOrderDetail.get("resumeClassID").toString());

        DecimalFormat df1 = new DecimalFormat("######0.00");
        request.setAttribute("balance", df1.format(balance.subtract(wMoney.multiply(tMoney))));

        request.setAttribute("record", record);

        request.setAttribute("flag", flag);
        request.setAttribute("userID", userID);

        return returnValue;
    }
}